<?php

/**
 * This is the model class for table "transactions".
 *
 * The followings are the available columns in table 'transactions':
 * @property integer $id
 * @property string $type
 * @property integer $user_id
 * @property double $cash
 * @property double $vcash
 * @property double $rate
 * @property string $from
 * @property string $from_detail
 * @property string $tran_cert
 * @property string $created_at
 *
 * The followings are the available model relations:
 * @property User $user
 */
class Transaction extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Transactions the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'transactions';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('type, user_id, cash, vcash, tran_cert, created_at', 'required'),
			array('user_id', 'numerical', 'integerOnly'=>true),
			array('cash, vcash, rate', 'numerical'),
			array('type, from', 'length', 'max'=>50),
			array('tran_cert', 'length', 'max'=>128),
			array('from_detail', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, type, user_id, cash, vcash, rate, from, from_detail, tran_cert, created_at', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'type' => 'Type',
			'user_id' => 'User',
			'cash' => 'Cash',
			'vcash' => 'Vcash',
			'rate' => 'Rate',
			'from' => 'From',
			'from_detail' => 'From Detail',
			'tran_cert' => 'Tran Cert',
			'created_at' => 'Created At',
		);
	}
	
	public function beforeSave() {
		$this->created_at = date('Y-m-d H:i:s');
		return parent::beforeSave();
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('cash',$this->cash);
		$criteria->compare('vcash',$this->vcash);
		$criteria->compare('rate',$this->rate);
		$criteria->compare('from',$this->from,true);
		$criteria->compare('from_detail',$this->from_detail,true);
		$criteria->compare('tran_cert',$this->tran_cert,true);
		$criteria->compare('created_at',$this->created_at,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * All type of deposit/withdraw
	 */
	public static function getType($type = null) {
		$arrType = array(
			'wmz'=>'Webmoney',
			'pm'=>'Perfect Money',
			'bk'=>'Bảo Kim',
			'nl'=>'Ngân Lượng',
			'sms'=>'SMS',
			'mcard'=>'Thẻ điện thoại',
			'gcard'=>'Thẻ game'
		);
		if(!empty($type)) {
			if(@$arrType[$type]) return $arrType[$type];
		}
		return $arrType;
	}
	
	public function successPayment($deposit=array()) {
		if(!count($deposit)) return;
		$modelUser = User::model()->findByAttributes(array('code'=>$deposit['code_deposit']));
		if(!is_object($modelUser)) return;
		$tran_cert = $modelUser->tran_cert;
		$amountUser= crypt($modelUser->amount, $modelUser->tran_cert);
		if($amountUser!=$tran_cert) return;
		//insert transactions
		$model = new Transaction();
		$model->type = 'deposit';
		$model->code = $deposit['code_deposit'];
		$model->cash = $deposit['amount_transfer'];
		$model->vcash = $deposit['amount_receive'];
		$model->rate = $deposit['rate'];
		$model->from = $deposit['type'];
		$model->from_detail = $deposit['payer'];
		$model->insert();
		//update amount
		$modelUser->amount+=$deposit['amount_receive'];
		$modelUser->tran_cert = crypt($modelUser->amount, blowfishSalt());
		$modelUser->update();
	}


	public function sendMailTransfer(){
		$subject = Yii::t('msg', '0036');
		$link = Yii::app()->params['domain'].Yii::app()->createUrl('bank/confirmTransfer?code='.$this->code.'&tran_code='.$this->tran_cert);

		$mail = new YiiMailer();
		$mail->setView('mailTransfer');
		$mail->setData(array(
			'link' => $link,
			'code' => $this->code,
			'amount' => $this->vcash,
			'transfer_rate' => $this->rate,
			'name' => Yii::app()->user->getState('current_user')->username
		));

		$mail->setFrom(Yii::app()->params['noreplyMail']);
		$mail->setTo(Yii::app()->user->getState('current_user')->email);
		$mail->setSubject($subject);

        return $mail->send();
	}

	public function transfer($to, $amount, $rate_transfer){
		$tran = new Transaction;
		$tran->type = "transfer";
		$tran->code = $to;
		$tran->vcash= $amount;
		$tran->rate = $rate_transfer;
		$tran->from = 'user_transfer';
		$tran->from_detail = Yii::app()->user->getState('current_user')->code;
		$tran->tran_cert = md5(time().$amount);
		$tran->insert();
		$tran->sendMailTransfer();
		return true;
	}

	public function confirmTransfer(){
		$transaction =  Yii::app()->db->beginTransaction();
		try{
		   $current_user = User::model()->findByAttributes(array('code' => $this->from_detail));
		   $to_user   = User::model()->findByAttributes(array('code' => $this->code));
		   if(!is_object($to_user)){
		   		throw new Exception(Yii::t('msg', '0043', array()), 1);
		   }
		   $final_price = $this->vcash + ceil($this->vcash * ($this->rate / 100));
		   $current_user->amount -= $final_price;
		   $current_user->update();
		   $to_user->amount += $final_price;
		   $to_user->update();
		   $this->archived = true;
		   $this->update();
		   $transaction->commit();
		}catch(Exception $e)
		{
		   $transaction->rollback();
		   return false;
		}
		return true;
	}
}